import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:mall/core/models/store_categories.dart';
import 'package:mall/core/services/api.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../product/product_category_screen.dart';

class StoreCategory extends StatefulWidget {
  final int storeId;
  final bool selectable;

  const StoreCategory({
    Key key,
    @required this.storeId,
    this.selectable = false,
  }) : super(key: key);

  @override
  _StoreCategoryState createState() => _StoreCategoryState();
}

class _StoreCategoryState extends State<StoreCategory> {
  String _error;
  List<Category> _list;

  @override
  void initState() {
    super.initState();
    _fetchCategory();
  }

  @override
  Widget build(BuildContext context) {
    return _error == null && _list == null
        ? Center(
            child: CircularProgressIndicator(),
          )
        : _list == null
            ? Center(child: Text("$_error"))
            : _buildBody();
  }

  Widget _buildBody() {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(vertical: 8.w),
      child: Wrap(
        runSpacing: 8.w,
        children: List.generate(_list.length, (index) => _buildItem(_list[index])),
      ),
    );
  }

  Widget _buildItem(Category category) {
    return GestureDetector(
      onTap: () => _onTapItemOrChildItem(category),
      child: Container(
        color: Colors.white,
        padding: EdgeInsets.all(8.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text("${category.name}"),
                Image.asset("assets/image/arrow_right.png", width: 24.w, height: 24.w),
              ],
            ),
            SizedBox(height: 8.w),
            Wrap(
              spacing: 8.w,
              runSpacing: 8.w,
              children: List.generate(
                category.children.length,
                (index) => _buildChildItem(category.children[index]),
              ),
            ),
            SizedBox(height: 8.w),
          ],
        ),
      ),
    );
  }

  Widget _buildChildItem(Category category) {
    return GestureDetector(
      onTap: () => _onTapItemOrChildItem(category),
      child: Container(
        padding: EdgeInsets.all(4.w),
        width: ((375.0 - 8 * 3) / 2).w,
        decoration: BoxDecoration(
          color: Theme.of(context).scaffoldBackgroundColor,
          borderRadius: BorderRadius.circular(4.w),
        ),
        child: Text(
          "${category.name}",
          style: TextStyle(fontSize: 12.sp),
        ),
      ),
    );
  }

  /// 点击分类
  void _onTapItemOrChildItem(Category category) {
    // 需要判断是否选择
    if (widget.selectable) {
      Navigator.of(context).pop(category);
    } else {
      Navigator.of(context).pushNamed(
        ProductCategoryScreen.routeName,
        arguments: ProductCategoryScreenArgs(
          "${category.name}",
          storeId: widget.storeId,
          categoryId: category.id,
        ),
      );
    }
  }

  /// 获取商品分类
  void _fetchCategory() async {
    final api = context.read<Api>();
    try {
      final categories = await api.category(2, null, storeId: widget.storeId);
      if (!mounted) {
        return;
      }
      setState(() {
        _list = categories.childCategoriesV2;
      });
    } on DioError catch (e) {
      if (!mounted) {
        return;
      }
      setState(() {
        _error = e.message;
      });
    } catch (e) {
      debugPrint("$e");
    }
  }
}
